#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int tickets = 100;
pthread_mutex_t mutex;
void *getTickets(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            cout << name << " 抢到了票, 票的编号: " << tickets << endl;
            tickets--;
            pthread_mutex_unlock(&mutex);
            usleep(123); //模拟其他业务逻辑的执行
        }
        else
        {
            cout << name << "] 已经放弃抢票了，因为没有了..." << endl;
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_mutex_init(&mutex,nullptr);
    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    pthread_t tid4;
    pthread_create(&tid1, nullptr, getTickets, (void *)"thread 1");
    pthread_create(&tid2, nullptr, getTickets, (void *)"thread 2");
    pthread_create(&tid3, nullptr, getTickets, (void *)"thread 3");
    pthread_create(&tid4, nullptr, getTickets, (void *)"thread 4");

    int n = pthread_join(tid1, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid2, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid3, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid4, nullptr);
    cout << n << ":" << strerror(n) << endl;
    pthread_mutex_destroy(&mutex);
    return 0;
}